package com.school.component.security;

import com.school.model.Role;
import com.school.model.RolePermission;
import com.school.model.User;
import com.school.model.UserRole;
import com.school.service.impl.RolePermissionServiceImpl;
import com.school.service.impl.RoleServiceImpl;
import com.school.service.impl.UserRoleServiceImpl;
import com.school.service.impl.UserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.*;

@Service
public class SpringSecurityUserServiceImpl implements UserDetailsService {
    @Autowired
    private UserServiceImpl userService;
    @Autowired
    private UserRoleServiceImpl userRoleService;
    @Autowired
    private RoleServiceImpl roleService;
    @Autowired
    private RolePermissionServiceImpl rolePermissionService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        if (!StringUtils.hasText(username)) {
            throw new UsernameNotFoundException("用户名为空，请检查参数！");
        }
        User user = userService.queryByUsername(username);
        List<UserRole> userRoles = userRoleService.queryByUserId(user.getId());
        List<Role> roles = new LinkedList<>();
        for (UserRole userRole : userRoles) {
            Integer roleId = userRole.getRoleId();
            roles.add(roleService.queryById(roleId));
        }

        Collection<GrantedAuthority> roles_ = new HashSet();
        Iterator<Role> roleIterator = roles.iterator();
        Role role = null;
        while (roleIterator.hasNext()) {
            role = (Role) roleIterator.next();
            List<RolePermission> rolePermissions = rolePermissionService.queryByRoleId(role.getId());
                for (RolePermission rolePermission : rolePermissions) {
                    roles_.add(new SimpleGrantedAuthority(rolePermission.getPermission()));
                }
            roles_.add(new SimpleGrantedAuthority(role.getName()));
        }
        return new org.springframework.security.core.userdetails.User(username,  user.getPassword(), roles_);
    }
}
